package com.xuyu.common.tool.fsm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * 状态机的配置类
 *
 * @param <S> 状态
 * @param <E> 事件
 */
public class FsmConfigurer<S, E> {

    private S from;

    private S to;

    private E event;

    private List<Function<?, ?>> eventProcessor;

    /**
     * 一些可以自己定义的参数
     */
    private Map<String, Object> properties;


    public FsmConfigurer() {
    }

    public FsmConfigurer<S, E> from(S from) {
        this.from = from;
        return this;
    }

    public FsmConfigurer<S, E> to(S to) {
        this.to = to;
        return this;
    }

    public FsmConfigurer<S, E> event(E event) {
        this.event = event;
        return this;
    }


    public FsmConfigurer<S, E> eventProcessor(Function<?, ?> process) {
        if (isEmptyList(eventProcessor)) {
            eventProcessor = new ArrayList<>();
        }
        eventProcessor.add(process);
        return this;
    }


    public E getEvent() {
        return this.event;
    }

    public List<Function<?, ?>> getHandlers() {
        return eventProcessor;
    }

    private boolean isEmptyList(List<?> list) {
        return list == null || list.size() == 0;
    }


    public FsmConfigurer<S, E> setProperties(String key, Object value) {
        if (properties == null) {
            properties = new HashMap<>();
        }
        properties.put(key, value);
        return this;
    }

    public Object getProperty(String key) {
        if (properties == null) {
            return null;
        }
        return properties.get(key);
    }


    public S getTo() {
        return to;
    }
}
